package com.aoxiang.zbox.config.filter;

import com.aoxiang.zbox.common.DataSourceContextHolder;
import com.aoxiang.zbox.common.UserContextHolder;
import com.aoxiang.zbox.config.DataSourceConfig;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class SetDataSourceFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String path = request.getRequestURI();

        try {
            if (path.startsWith("/api/user")) {
                // 这些请求使用默认数据源
                DataSourceContextHolder.setDefaultDataSource();
            } else {
                // 其他请求，获取 userId 进行数据源切换
                Long userId = UserContextHolder.getUser().getId();
                if (userId != null) {
                    String userDatabaseKey = DataSourceConfig.getUserDatabaseKey(userId);
                    DataSourceContextHolder.setDataSource(userDatabaseKey);
                } else {
                    DataSourceContextHolder.setDefaultDataSource();
                }
            }

            filterChain.doFilter(request, response);
        } finally {
            // 确保在请求结束时清除数据源，防止污染其他线程
            DataSourceContextHolder.clearDataSource();
        }
    }


    @Override
    public void destroy() {

    }
}
